#!/bin/bash
set -xe

STUDY_NAME=$1
TRIAL_NUMBER=$2
TARGET_PRODUCT=$3
CONFIG_PATH=$4
TRADING_DATES=$5
HOURS=${6:-24H}
CMDS=()

source ../coin_binary/fastfeature/third_party/fastfeature/bin/envsetup.sh
tmp_dir=$(mktemp -d -t ci-XXXXXXXXXX)

function run_sim() {

DRIVER_CONFIG=$(mktemp /tmp/lm_strategy.driver.XXXXXXX.json)
LM_STRAT_CONFIG=$(mktemp /tmp/lm_strategy.lm_strat.XXXXXXX.json)
TRADING_DATE=$1

./pyrunner python/coin_deploy/lm_agg2/lm_strategy_conf_generator.py \
--config_path=$CONFIG_PATH \
--out_driver_json=$DRIVER_CONFIG \
--out_lm_strat_json=$LM_STRAT_CONFIG \
--sim_setting_json=data/coin2/sim/sim_setting.json \
--sim_report=RESULT_FORMAT_PNL_JSON_PRINT_AND_PROTO_DUMP \
--lm_logic=lm-agg \
--archive_type=FASTFEED \
--archive_date=$TRADING_DATE \
--archive_duration=$HOURS \
--order_system_type=ORDER_SYSTEM_TYPE_SIM_OG \
> /dev/null

CMDS+=("./bazel-bin/cc/appcoin2/strategy/lm/sim \
--driver=$DRIVER_CONFIG \
--lm_strat_json=$LM_STRAT_CONFIG \
--sim_result_filepath=$tmp_dir/$TRADING_DATE.pb")
}

int_handler()
{
    echo "Interrupted."
    # Kill the parent process of the script.
    kill $(ps -o pid= --ppid $$)
    kill $PPID
    exit 1
}
trap 'int_handler' INT


CMD_GEN=`python -c "import pandas; dt=pandas.DatetimeIndex('${TRADING_DATES}'.split('-')); print('; \n'.join(['run_sim %s' % dtstr for dtstr in pandas.date_range(*dt).strftime('%Y%m%d')]))"`
eval $CMD_GEN

parallel -k ::: "${CMDS[@]}"

PLOT_DIR="/scratch/local/out/$STUDY_NAME"
mkdir -p $PLOT_DIR

if [[ $CONFIG_PATH =~ "okex" || $CONFIG_PATH =~ "Okex"  ]]; then
	feed_machine=feed-05.cn-hongkong.aliyun
else
	feed_machine=feed-05.ap-northeast-1.aws
fi

./pyrunner \
python/coin/pnl/sim_stat_frompb.py \
--pb_path "$tmp_dir/*.pb" \
--feed_machine "$feed_machine" \
--api_override=Spot:Huobi=v1.snapshot,Futures:Huobi=v1.incremental,Futures:Okex=v3.realtime,Futures:Binance=v1.l1_realtime \
--sim_result_dir $PLOT_DIR \
--sim_result_prefix "trial$TRIAL_NUMBER" \
--use_feed_cache True \
1>/dev/null

